package com.rzt.cft.admin.controller.project;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rzt.cft.admin.aspect.SysLog;
import com.rzt.cft.admin.controller.BaseController;
import com.rzt.cft.constant.ServiceStatus;
import com.rzt.cft.constant.TypeConstant;
import com.rzt.cft.dto.ResponseData;
import com.rzt.cft.dto.project.ProjectDetailDto;
import com.rzt.cft.dto.project.ProjectOrderDto;
import com.rzt.cft.entity.project.ProjectDetail;
import com.rzt.cft.entity.project.ProjectOrder;
import com.rzt.cft.entity.project.ProjectStatistics;
import com.rzt.cft.entity.uc.UcUser;
import com.rzt.cft.param.IdParam;
import com.rzt.cft.param.project.AddProjectDetailParam;
import com.rzt.cft.param.project.ProjectOrderPageParam;
import com.rzt.cft.param.uc.ProjectParam;
import com.rzt.cft.service.project.IProjectDetailService;
import com.rzt.cft.service.project.IProjectOrderService;
import com.rzt.cft.service.project.IProjectStatisticsService;
import com.rzt.cft.service.uc.IUcUserService;
import com.rzt.cft.utils.CustomUtil;
import com.rzt.cft.utils.ParseWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author 钟忠
 * @date 2020/2/5 11:51
 */
@RestController
@RequestMapping("/v1/project")
@Api(tags = "项目相关接口")
public class ProjectController extends BaseController {


    @Autowired
    private IProjectDetailService projectDetailService;

    @Autowired
    private IProjectStatisticsService projectStatisticsService;

    @Autowired
    private IProjectOrderService projectOrderService;

    @Autowired
    private IUcUserService ucUserService;

    @ApiOperation("项目列表(分页)")
    @PostMapping("/list")
    public ResponseData<IPage<ProjectDetailDto>> list(@RequestBody ProjectParam para) {
        Page page = getPage(para);
        QueryWrapper<ProjectDetail> queryWrapper =  ParseWrapper.parseWrapper(para);
        queryWrapper.orderByDesc("create_at");
        IPage<ProjectDetail> detailIPage = projectDetailService.page(page, queryWrapper);
        List<String> ids = CustomUtil.select(detailIPage.getRecords(), ProjectDetail::getId);
        QueryWrapper<ProjectStatistics> statisticsQueryWrapper =  new QueryWrapper<>();
        statisticsQueryWrapper.eq("current", true);
        statisticsQueryWrapper.in("project_id", ids);
        List<ProjectStatistics> statistics = projectStatisticsService.list(statisticsQueryWrapper);
        IPage<ProjectDetailDto> projectDtoIPage = detailIPage.convert(x -> CustomUtil.maping(x, ProjectDetailDto.class));
        projectDtoIPage.getRecords().forEach(x -> {
            ProjectStatistics projectStatistics = CustomUtil.first(statistics, m -> m.getProjectId().equals(x.getId()));
            if (Objects.nonNull(projectStatistics)) {
                x.setVirtualProgress(projectStatistics.getVirtualProgress());
                x.setRealProgress(projectStatistics.getRealProgress());
            }
        });
        return success(projectDtoIPage);
    }

    @ApiOperation("添加项目")
    @PostMapping("/add")
    @SysLog("添加项目")
    public ResponseData<Boolean> add(@RequestBody AddProjectDetailParam param) {
        if (!param.getType().equals(TypeConstant.projectType.OPTIONAL)
                && !param.getType().equals(TypeConstant.projectType.INTELLIGENCE)) {
            return fail(ServiceStatus.WRONG_PROJECT_TYPE);
        }
        if (param.getIsRecommend() != null && param.getIsRecommend()) {
            QueryWrapper<ProjectDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_recommend", true);
            queryWrapper.eq("type", param.getType());
//            queryWrapper.eq("status", StatusConstant.ProjectOrderStatus);
            List<ProjectDetail> projectDetails = projectDetailService.list(queryWrapper);
            if (projectDetails.size() >= 5) {
                return fail(ServiceStatus.NO_MORE_THAN_5_SELECTED_PROJECTS);
            }
        }
        Boolean result = projectDetailService.add(param);
        return success(result);
    }

    @ApiOperation("项目删除")
    @PostMapping("/delete")
    @SysLog("项目删除")
    public ResponseData<Boolean> memberDelete(@RequestBody String... ids) {
        Boolean result = projectDetailService.removeByIds(Arrays.asList(ids));
        return success(result);
    }

    @ApiOperation("修改项目")
    @PostMapping("/update")
    @SysLog("修改项目")
    public ResponseData<Boolean> update(@RequestBody AddProjectDetailParam param) {
        ProjectDetail old = projectDetailService.getById(param.getId());
        if (Objects.isNull(old)) {
            return fail(ServiceStatus.PARAM_EXCEPTION);
        }

        if (param.getIsRecommend() != null && param.getIsRecommend()) {
            QueryWrapper<ProjectDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_recommend", true);
            queryWrapper.eq("type", old.getType());
//            queryWrapper.eq("status", StatusConstant.ProjectOrderStatus);
            List<ProjectDetail> projectDetails = projectDetailService.list(queryWrapper);
            if (projectDetails.size() >= 5) {
                return fail(ServiceStatus.NO_MORE_THAN_5_SELECTED_PROJECTS);
            }
        }

        Boolean result = projectDetailService.update(param);
        return success(result);
    }

    @ApiOperation("项目详情")
    @PostMapping("/detail")
    public ResponseData<ProjectDetailDto> detail(@RequestBody IdParam para) {
        ProjectDetail projectDetail = projectDetailService.getById(para.getId());
        if (Objects.isNull(projectDetail)) {
            return fail(ServiceStatus.PARAM_EXCEPTION);
        }
        ProjectDetailDto projectDetailDto = CustomUtil.maping(projectDetail, ProjectDetailDto.class);
        QueryWrapper<ProjectStatistics> statisticsQueryWrapper =  new QueryWrapper<>();
        statisticsQueryWrapper.eq("current", true);
        statisticsQueryWrapper.in("project_id", projectDetail.getId());
        ProjectStatistics projectStatistics = projectStatisticsService.getOne(statisticsQueryWrapper);
        projectDetailDto.setRealProgress(projectStatistics.getRealProgress());
        projectDetailDto.setVirtualProgress(projectStatistics.getVirtualProgress());
        return success(projectDetailDto);
    }

    @ApiOperation("注资合约列表")
    @PostMapping("/capitalInjection/list")
    public ResponseData<IPage<ProjectOrderDto>> capitalInjectionList(@RequestBody ProjectOrderPageParam param) {
        Page page = getPage(param);
        QueryWrapper<ProjectOrder> queryWrapper =  ParseWrapper.parseWrapper(param);
        queryWrapper.orderByDesc("create_at");
        IPage<ProjectOrder> orderIPage = projectOrderService.page(page, queryWrapper);
        List<String> ids = CustomUtil.select(orderIPage.getRecords(), ProjectOrder::getUserId);
        IPage<ProjectOrderDto> orderDtoIPage = orderIPage.convert(x -> CustomUtil.maping(x, ProjectOrderDto.class));
        if (ids.size() == 0) {
            return success(orderDtoIPage);
        }
        List<UcUser> ucUserList = ucUserService.listByIds(ids);
        orderDtoIPage.getRecords().forEach( x -> {
            UcUser ucUser = CustomUtil.first(ucUserList, m -> x.getUserId().equals(m.getId()));
            if (Objects.nonNull(ucUser)) {
                x.setUserAccount(ucUser.getAccount());
            }
        });
        return success(orderDtoIPage);
    }

    @ApiOperation("订单详情")
    @PostMapping("/capitalInjection/detail")
    public ResponseData<ProjectOrderDto> capitalInjectionDetail(@RequestBody IdParam para) {
        ProjectOrder projectOrder = projectOrderService.getById(para.getId());
        if (Objects.isNull(projectOrder)) {
            return fail(ServiceStatus.PARAM_EXCEPTION);
        }
        return success(CustomUtil.maping(projectOrder, ProjectOrderDto.class));
    }


}
